(in-package :netrisd)

(defvar *interface* #(127 0 0 1))
(defvar *port* 9284)
(defvar *server* nil)


;; open a server port 

(defun netris-server (&key (interface *interface*) (port *port*) (backlog 5)) 
   "Returns a socket server bound to PORT on INTERFACE.  Defaults to   
(machine-instance):8000. 
   The queue size BACKLOG defaults to 5 connections." 
   (handler-case 
     (let ((server (make-instance 'inet-socket :type :stream :protocol :tcp))) 
       (socket-bind server interface port) 
       (socket-listen server backlog) 
       server) 
     (address-in-use-error () 
                           (error (format nil "address ~A : ~A is already in use" interface port))
                           (force-output) 
                           nil))) 

;; return a connection 

(defun netris-accept (server) 
   (when server 
     (socket-accept server)))

(defun make-new-player (socket)
    (format t "Making new player~%")
    (with-packets (version) socket 
		  (with-packet version
		    (if (and (= type NP_version) 
				 (equal (mapcar #'list-to-num 
						(multiple-value-list 
						 (first-n 4 data)))
					(list MAJOR_VERSION PROTOCOL_VERSION)))
			(add-player socket)
			(progn
			  (format t "Invalid initial packet, disconnecting ~A." (socket-peername socket))
			  (socket-close socket))))))

(defun start-netrisd ()
  (format t "Starting netrisd~%")
  (setf *server* (netris-server))
  (loop do 
   (let ((socket (netris-accept *server* )))
     (sb-thread:make-thread (lambda () (make-new-player socket))))))
